<template>
	<view class="y-flex y-flex-1">
		<com-status-bar v-if="pageStyle.enableNavigationTransparent" color="#000000"></com-status-bar>
		<!-- <web-view ref="webview" v-if="videoplayer == 'H5'"
		@onPostMessage="onPostMessage"
		:style="{
			height: '380rpx'
		}"
		src="/hybrid/html/h5player.html"></web-view> -->
		<video
		v-if="src"
		:is-live="isLive"
		ref="video"
		class="video"
		enable-play-gesture
		:initial-time="initialTime"
		:autoplay="autoplay"
		:enable-danmu="barrages.length > 0"
		danmu-btn
		show-mute-btn
		:poster="poster"
		:danmu-list="barrages"
		:title="name"
		:style="{
			height: '380rpx'
		}"
		:src="src"
		@ended="handleEnded"
		@error="handleError"
		@timeupdate="handleTimeupdate">
			<view class="position-absolute-cover y-flex y-align-center y-justify-center" v-if="playend">
				<text class="fs-28 fr-fff">播放结束</text>
			</view>
			<view class="position-absolute-cover y-flex y-align-center y-justify-center" v-else-if="error">
				<text class="fs-28 fr-fff" @tap="handleCopy(src)">加载失败：{{src}}</text>
			</view>
		</video>
		<module-list
		ref="list"
		:data="components"
		:cell="cell"
		:bounce="pageStyle.enableBounce"
		:back-top-show="pageStyle.enableBackTop"
		:refreshImage="pageStyle.pulldownRefreshImage"
		:pulldownable="pageStyle.enablePulldown == 1"
		:loadmoreable="pageStyle.enableLoadmore == 1"
		:loadingColor="pageStyle.loadingColor"
		:backTopImage="pageStyle.backTopImage"
		:marginGap="pageStyle.pageMarginGap"
		:params="detail"
		@pulldown="handlePulldown"
		@loaded="handleModuleLoaded">
			<template #top v-if="detail && detail.uniqueId">
				<cell>
					<view class="y-flex" :style="{'padding-left': pageMarginGap, 'padding-right': pageMarginGap}">
						<text class="fs-30 mt-20" :style="{color: skinColor.color_1}">{{detail.title}}</text>
						<text class="fs-26 mt-20" :style="{color: skinColor.color_3}" v-if="detail.subtitle">{{detail.subtitle}}</text>
						<com-read-more class="mt-20" font-size="28" line-height="50" :color="skinColor.color_3" :shadowColor="pageStyle.background" :text="detail.description" v-if="detail.description"></com-read-more>
						<scroll-view class="y-flex y-row y-align-center mt-20" :show-scrollbar="false" scroll-x v-if="detail.tags">
							<view class="find_novel_tag mr-20" v-for="(item, index) in detail.tags" :key="index" :style="{'border-color': themeColor}" @tap="handleTagTap(item)">
								<text class="fs-24" :style="{color: themeColor}">{{item.title}}</text>
							</view>
						</scroll-view>
						<com-grid class="mt-30" :data="items" :column="itemsColumn" :count="3 * itemsColumn" v-if="items.length > 1">
							<template v-slot="{item, index}">
								<view class="y-flex y-flex-1 y-align-center y-justify-center pt-20 pb-20 border-1"
								:style="{'border-color': current == index ? themeColor : skinColor.color_2}" @tap="handleChange(index)">
									<text class="fs-24" :style="{color: current == index ? themeColor : skinColor.color_2}">第{{index+1}}集</text>
								</view>
							</template>
						</com-grid>
						<view class="y-flex y-row y-align-center y-justify-center mt-20" v-if="items.length > 12" @tap="handleShowFullItems">
							<com-icon name="unfold" size="26" :color="skinColor.color_blue"></com-icon>
							<text class="fr-primary fs-22 ml-10">全部剧集</text>
						</view>
					</view>
				</cell>
			</template>
			<template #center v-if="showComment">
				<cell>
					<com-gap></com-gap>
					<view class="y-flex y-row y-align-center find_novel_border pb-20 pt-20 pl-20 pr-20"
					:style="{'border-bottom-color': skinColor.color_gap_1 ,'background-color': boxBgColor,'margin-left': pageMarginGap, 'margin-right': pageMarginGap}">
						<text class="fs-35 y-flex-1 fw-bold" :style="{color: skinColor.color_1}">评论列表</text>
					</view>
				</cell>
			</template>
		</module-list>
		<com-popup :visible.sync="fullItemsShow" direction="bottom">
			<view class="y-flex" :style="{'background-color': skinColor.color_bg_1, 'height': modalHeight + 'px'}">
				<view class="y-flex y-row y-align-center pt-20 pb-20 page-padding-gap border-bottom-1" :style="{'border-bottom-color': skinColor.color_gap_1}">
					<text class="fs-28 y-flex-1" :style="{color: skinColor.color_1}">选集（{{items.length}}）</text>
					<com-icon name="close" size="40" :color="skinColor.color_2" @click="fullItemsShow = false"></com-icon>
				</view>
				<com-list class="y-flex-1">
					<cell v-for="(grid, i) in Math.ceil(items.length / itemsColumn)" :key="i">
						<com-grid :data="items.slice(i * itemsColumn, (i + 1) * itemsColumn)"
						:column="itemsColumn"
						:count="itemsColumn"
						class="mt-20"
						:style="{'margin-left':  pageMarginGap, 'margin-right':  pageMarginGap}">
							<template v-slot="{item, index}">
								<view class="y-flex y-flex-1 y-align-center y-justify-center pt-20 pb-20 border-1"
								:style="{'border-color': current == ((i * itemsColumn) + index) ? themeColor : skinColor.color_2}" @tap="handleChange((i * itemsColumn) + index)">
									<text class="fs-24" :style="{color: current == ((i * itemsColumn) + index) ? themeColor : skinColor.color_2}">第{{(i * itemsColumn) + index + 1}}集</text>
								</view>
							</template>
						</com-grid>
					</cell>
				</com-list>
				<com-gap></com-gap>
			</view>
		</com-popup>
	</view>
</template>

<script>
	import ModuleList from './components/ModuleList.vue'
	import { openDB, closeDB, select, insert, update, remove } from '@/assets/database'
	import { timeFormat, copyText } from '@/assets/js/util.js'
	export default {
		inject: ['getSkinColor', 'getPage', 'getBoxBgColor', 'getPageStyle', 'navigate', 'getQuery', 'download', 'confirm'],
		components: {
			ModuleList
		},
		computed: {
			videoplayer () {
				return this.$store.getters['setting/GET_VIDEO_PLAYER']
			},
			autoplay () {
				return this.$store.getters['setting/GET_VIDEO_AUTOPLAY']
			},
			history () {
				return this.$store.getters['setting/GET_HISTORY']
			},
			skinColor () {
				return this.getSkinColor()
			},
			//路由参数
			query () {
				return this.getQuery()
			},
			app () {
				return getApp().globalData
			},
			page () {
				return this.getPage()
			},
			pageStyle () {
				return this.getPageStyle()
			},
			components () {
				return this.page?.components || []
			},
			cell () {
				return Object.assign({}, this.page?.comments || {}, {style: {cellName: 'comment-cell', cellGap: 0}})
			},
			boxBgColor () {
				return this.getBoxBgColor()
			},
			boxBorderRadius () {
				return this.pageStyle.componentBorderRadius
			},
			coverWidth () {
				return this.pageStyle.coverWidth || ''
			},
			coverHeight () {
				return this.pageStyle.coverHeight || 242
			},
			network () {
				return this.$store.getters['network/GET']
			},
			//页面左右边距
			pageMarginGap () {
				return this.app.$utils.pixelunit(this.pageStyle?.pageMarginGap)
			},
			topPageMarginGap () {
				return (this.app.$utils.unitpixel(this.pageStyle?.pageMarginGap) + uni.upx2px(20)) + 'px'
			},
			//主题色
			themeColor () {
				return this.pageStyle.themeColor || this.skinColor.color_blue
			},
			content () {
				return `<div style="color: ${this.skinColor.color_1}">` + this.detail.content + '</div>'
			}
		},
		data () {
			return {
				detail: {},//详情信息
				items: [],//分集列表
				itemsColumn: 4,//分集栏数
				barrages: [],//弹幕列表
				name: '',//标题
				src: '',//播放链接
				poster: '',//封面
				playend: false,//播放结束
				error: false,//加载失败
				isLive: false,//是否直播链接
				showComment: false,//显示评论列表
				fullItemsShow: false,//展示完整剧集
				modalHeight: 0,//高度
				current: 0,//当前播放索引
				playTime: 0,//播放时间
				initialTime: 0,//初始播放时间
				record: {}//历史记录
			}
		},
		mounted () {
			this.$nextTick(this.handlePulldown)
		},
		methods: {
			onShow () {
				this.$refs.video && this.$refs.video.play()
				if ( this.detail.uniqueId ) this.getRecord()
			},
			onHide () {
				this.$refs.video && this.$refs.video.pause()
			},
			onBackPress () {
				if ( this.fullItemsShow ) {
					this.fullItemsShow = false
					return true
				}
				if ( this.detail.uniqueId && this.playTime > 0 ) {
					if ( this.history == 0 ) {
						this.confirm({
							title: '记录提示',
							content: '当前观看到第' + (this.current + 1) + '集-' + timeFormat(this.playTime) + '是否记录当前观看位置',
							cancelText: '取消记录',
							confirmText: '保存记录',
							success: res => {
								if ( res.confirm ) {
									this.saveRecord()
								} else {
									this.app.$Router.back()
								}
							}
						})
					} else if ( this.history == 1 ) this.saveRecord()
					else this.app.$Router.back()
					return true
				}
				return false
			},
			async saveRecord () {
				await openDB()
				try{
					if ( this.record.id ) {
						await update('record', {
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							current: this.current,
							position: this.playTime,
							currentTitle: this.name,
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						}, 'id = ' + this.record.id)
					} else {
						await insert('record', {
							unique_id: this.detail.uniqueId,
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							current: this.current,
							position: this.playTime,
							currentTitle: this.name,
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						})
					}
					closeDB()
					this.app.$Router.back()
				}catch(e){
					closeDB()
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
					setTimeout(() => {
						this.app.$Router.back()
					}, 500)
				}
			},
			async getRecord () {
				try{
					await openDB()
					const data1 = await select('record', 'unique_id = "' + this.detail.uniqueId + '"')
					this.record = data1.list[0] || {}
					if ( this.items.length > 0 && !this.src ) this.handleChange(this.record.current || 0, this.record.position)
					const data2 = await select('collection', 'unique_id = "' + this.detail.uniqueId + '"')
					const utils = [{
						label: data2.count > 0 ? '已收藏' : '点击收藏',
						icon: data2.count > 0 ? 'favor_fill' : 'favor',
						color: data2.count > 0 ? this.skinColor.color_red : '',
						func: async () => {
							try{
								await openDB()
								if ( data2.count > 0 ) {
									await remove('collection', 'id = ' + data2.list[0].id)
									uni.showToast({
										title: '取消收藏成功',
										icon: 'none'
									})
									await closeDB()
									this.getRecord()
								} else {
									const params = {
										unique_id: this.detail.uniqueId,
										url: this.detail.url,
										title: this.detail.title || '',
										cover: this.detail.cover || '',
										is_adult: this.detail.isAdult || 0,
										source_id: this.detail.sourceId
									}
									await insert('collection', params)
									uni.showToast({
										title: '收藏成功',
										icon: 'none'
									})
									await closeDB()
									this.getRecord()
								}
							}catch(e){
								closeDB()
								uni.showToast({
									title: e.message,
									icon: 'none'
								})
							}
						}
					}]
					if ( this.detail.shareUrl && this.detail.title ) {
						utils.push({
							label: '分享资源',
							icon: 'forward',
							func: () => {
								this.app.$Router.push({
									path: '/pages/find/modules/poster',
									animationType: 'none',
									query: {
										params: this.detail
									}
								})
							}
						})
					}
					if ( this.detail.title && this.items.length > 0 ) {
						utils.push({
							label: '下载视频',
							icon: 'down',
							func: () => {
								if ( !this.src ) {
									uni.showToast({
										title: '请先播放视频',
										icon: 'none'
									})
									return
								}
								this.download({title: this.name, url: this.src, isAdult: this.detail.isAdult})
							}
						})
					}
					this.$emit('utils', utils)
				}catch(e){
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
				}
				closeDB()
			},
			handleScroll (e) {
				this.$emit('scroll', Math.abs(e.contentOffset.y))
			},
			handleTimeupdate (e) {
				this.playTime = e.detail.currentTime
			},
			handleEnded () {
				if ( this.current == this.items.length - 1 ) this.playend = true
				else this.handleChange(this.current+1)
			},
			handleError () {
				this.error = true
			},
			handleTagTap (item) {
				this.navigate(item.url)
			},
			handleCopy (src) {
				copyText(src)
			},
			async handleChange (current, time) {
				if ( this.current == current && this.src ) return
				this.$refs.video && this.$refs.video.stop()
				this.src = ''
				this.current = parseInt(current)
				let item = this.items[current]
				if ( !item.src && !item.loading ) {
					this.$set(this.items[current], 'loading', true)
					const newItem = await this.handleGetContext(item)
					newItem.barrages = await this.handleGetBarrages(newItem)
					this.$set(this.items[current], 'loading', false)
					this.$set(this.items, current, newItem)
					item = this.items[current]
				}
				if ( item.src ) {
					this.name = item.title || this.detail.title + '第' + (current + 1) + '集'
					this.poster = item.cover || this.detail.cover
					this.barrages = item.barrages || []
					this.initialTime = time || 0
					this.src = item.src
					this.isLive = item.isLive || false
				}
			},
			handleModuleLoaded () {
				this.$emit('loaded', true)
				this.$refs.list && this.$refs.list.pulldownSuccess()
				this.showComment = (this.$refs.list?.cells?.length || 0) > 0
			},
			async handlePulldown (callback) {
				try{
					this.detail = await this.handleGetDetail()
					this.items = await this.handleGetItems()
					this.$nextTick(function () {
						this.$refs.list && this.$refs.list.initModule(callback)
						if ( this.detail.uniqueId ) this.getRecord()
					})
				}catch(e){
					this.$emit('loaded', true)
				}
			},
			async handleGetDetail () {
				const detail = this.page?.detail || {}
				const staticData = this.network.staticDataHandle(detail.staticData || {}, this.query)
				const dynamicData = detail.dynamicData
				const request = detail.request
				let data = {}
				if ( dynamicData && request ) {
					const newRequest = this.network.requestHandle(request, this.query)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response)
					data.uniqueId = data.id || this.network.getUniqueId(newRequest)
					if ( !data.shareUrl && !staticData.shareUrl ) data.shareUrl = await this.network.getShareUrl(newRequest)
				}
				return Object.assign({}, staticData, data)
			},
			async handleGetItems () {
				const items = this.page?.items || {}
				const params = Object.assign({}, this.query, this.detail)
				const staticData = items.staticData ? this.network.staticDataHandle(items.staticData, params) : []
				const dynamicData = items.dynamicData
				const request = items.request
				let data = []
				if ( dynamicData && request ) {
					const newRequest = this.network.requestHandle(request, params)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response)
				}
				return staticData.concat(data).map(s => Object.assign({}, s, { loading: false, isLive: s.isLive == 1 ? true : s.isLive == 0 ? false : s.isLive }))
			},
			async handleGetContext (item) {
				const context = this.page?.context || {}
				const request = context.request
				const params = Object.assign({}, this.query, this.detail, item)
				const staticData = context.staticData ? this.network.staticDataHandle(context.staticData, params) : {}
				const dynamicData = context.dynamicData || {}
				const newRequest = request ? this.network.requestHandle(request, params) : null
				const response = newRequest ? await this.network.$request(newRequest) : null
				const data = response ? await this.network.$list(dynamicData, response) : null
				return Object.assign({}, item, staticData, data)
			},
			async handleGetBarrages (item) {
				const barrages = this.page?.barrages || {}
				const params = Object.assign({}, this.query, this.detail)
				const staticData = barrages.staticData ? this.network.staticDataHandle(barrages.staticData, params) : []
				const dynamicData = barrages.dynamicData
				const request = barrages.request
				let data = []
				if ( dynamicData && request ) {
					const newRequest = this.network.requestHandle(request, params)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response)
				}
				return staticData.concat(data)
			},
			handleShowFullItems () {
				const system = uni.getSystemInfoSync()
				this.modalHeight = system.windowHeight - uni.upx2px(100) - system.safeArea.top - uni.upx2px(380)
				this.fullItemsShow = true
			}
		}
	}
</script>

<style>
	.find_novel_cover {
		width: 228rpx;
		height: 322rpx;
	}
	.find_novel_border {
		border-bottom-width: 1px;
		border-bottom-style: dashed;
	}
	.find_novel_tag {
		border-width: 1px;
		border-style: solid;
		border-radius: 5rpx;
		padding: 4rpx 10rpx;
	}
</style>